package com.matthicks.macrobot;

import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.imageio.ImageIO;

public class CommandSender implements Commander {
	private Socket socket;
	private BufferedWriter writer;
	private DataInputStream input;
	
	public CommandSender(String host, int port) throws UnknownHostException, IOException {
		socket = new Socket(host, port);
		
		writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
		input = new DataInputStream(socket.getInputStream());
	}
	
	public CommandResponse processCommand(Command command) throws IOException, ClassNotFoundException {
		CommandResponse response = null;
		if (command.name.equals("quit")) {
			Controller.get().quit();
		} else {
			writer.write(command.toString());
			writer.newLine();
			writer.flush();
			
			boolean successful = input.readBoolean();
			response = new CommandResponse(successful);
			int payloadSize = input.readInt();
			if (payloadSize != -1) {
				byte[] buf = new byte[payloadSize];
				input.readFully(buf);
				ByteArrayInputStream bais = new ByteArrayInputStream(buf);
				ObjectInputStream ois = new ObjectInputStream(bais);
				response.payload = ois.readObject();
				
				if (response.payload instanceof ImageWrapper) {
					bais = new ByteArrayInputStream(((ImageWrapper)response.payload).data);
					response.payload = ImageIO.read(bais);
				}
			}
//			response.payloadType = input.readShort();
//			if (response.payloadType != CommandResponse.NO_PAYLOAD) {		// Payload
//				byte[] data = new byte[input.readInt()];
//				input.readFully(data);
//				if (response.payloadType == CommandResponse.IMAGE) {
//					ByteArrayInputStream bais = new ByteArrayInputStream(data);
//					response.payload = ImageIO.read(bais);
//				}
//			}
		}
		return response;
	}
	
	public void close() throws IOException {
		try {
			processCommand(new Command("disconnect()"));
			socket.close();
		} catch(Throwable t) {
		}
	}
}